package com.xms.security.api.controller;

import com.xms.core.config.FinalValueDefaults;
import com.xms.core.exception.XmsException;
import com.xms.security.api.model.UpdateRoleModel;
import com.xms.security.entity.Roles;
import com.xms.security.service.role.IRolesUpdaterService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import com.xms.web.framework.model.SetRecordStateModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.time.LocalDate;

/**
 * <p>
 * RolesUpdaterController
 * </p>
 *
 * @author migo
 * @since 2021/10/8
 */
@RestController
@RequestMapping("/{org}/api/security/role")
public class RolesUpdaterController extends ApiBaseController {
    private IRolesUpdaterService _rolesUpdaterService;

    @Autowired
    public void RolesUpdaterController(IRolesUpdaterService rolesUpdaterService) {
        _rolesUpdaterService = rolesUpdaterService;
    }

    @ApiOperation("修改安全角色")
    @PostMapping("update")
    public JsonResultObject update(@RequestBody UpdateRoleModel model) throws XmsException, SQLException {
        if (StringUtil.isEmpty(model.name) || UUIDUtil.isEmpty(model.roleid)) {
            return JNotSpecifiedParams("name", "id");
        }
        Roles entity = new Roles();
        entity.setRoleid(model.roleid);
        if (!model.roleid.equals(FinalValueDefaults.ADMIN_ROLEID)) {
            entity.setName(model.name);
            entity.setStatecode(model.statecode);
        } else if (model.name.toLowerCase().contains("admin")) {
            return JError("包含admin的名称已被系统保留，请另起名字");
        }
        entity.setDescription(model.description);
        entity.setModifiedon(LocalDate.now());
        entity.setModifiedby(_currentUser.getUser().SystemUserId);
        _rolesUpdaterService.update(entity);
        return JCreateSuccess();
    }

    @ApiOperation("设置安全角色可用状态")
    @PostMapping("setstate")
    public JsonResultObject setState(@RequestBody SetRecordStateModel model) {
        if (CollectionUtil.isEmpty(model.recordid)) {
            return JNotSpecifiedParams("id");
        }
        if (_rolesUpdaterService.updateState(model.isenabled, model.recordid)) {
            return JUpdateSuccess();
        }
        return JUpdateFailure();
    }
}
